#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

#include "head.h"
int qt_fd;

void *thread(void *arg)
{
    int recvbyte;
    MSG_t recv_msg;
    while(1)
    {
        recvbyte = recv(qt_fd,&recv_msg,sizeof(recv_msg),0);
        if(recvbyte < 0)
        {
            perror("recv error.");
           // return NULL;
        }
        printf("recv:%s %d %d %f %s\n", recv_msg.name, recv_msg.type, recv_msg.ival, recv_msg.fval,recv_msg.text);
    }
    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
#if 1
    if (argc != 3)
    {
        printf("please input %s <server_ip> <server_port>\n", argv[0]);
        return -1;
    }
    qt_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (qt_fd < 0)
    {
        perror("socket qt_fd error.");
        return -1;
    }
    struct sockaddr_in qtServeraddr;
    //1》填充hass通信server端结构体
    qtServeraddr.sin_family = AF_INET;
    qtServeraddr.sin_port = htons(atoi(argv[2]));
    qtServeraddr.sin_addr.s_addr = inet_addr(argv[1]);

    if(connect(qt_fd, (struct sockaddr *)&qtServeraddr, sizeof(qtServeraddr))< 0)
     {
        perror("connect error.");
        return -1;
     }
    pthread_t tid;
    pthread_create(&tid,NULL,thread,NULL);
    pthread_detach(tid);

#endif
    strcpy(msg.name, "hass");
    strcpy(msg.text, "hass!!!!!!");
    srand((float)time(NULL));
    while (1)
    {
        msg.type = rand() % 2;
        msg.type++;
        msg.ival = rand() % 10000;
      //  msg.fval = rand()%1000+((float)(rand() % 1001) * 0.001f);//获取0-10000随机小数
        send(qt_fd,&msg,sizeof(msg),0);
     //   printf("send:%s %d %d %f\n", msg.name, msg.type, msg.ival, msg.fval);
        sleep(1);
    }

    return 0;
}
